package com.sec.etech.chain.customergroup.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sec.etech.chain.customer.entity.ProjCustomer;
import com.sec.etech.chain.customer.mapper.ProjCustomerMapper;
import com.sec.etech.chain.customergroup.constant.CustomerGroupConstant;
import com.sec.etech.chain.customergroup.entity.CustomerGroup;
import com.sec.etech.chain.customergroup.mapper.CustomerGroupMapper;
import com.sec.etech.chain.customergroup.util.CustomerGroupUtil;
import com.sec.etech.common.fanutil.FanUtil;
import com.sec.etech.sys.util.ContextUtil;
import org.openbpm.base.core.id.IdUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class CustomerGroupService {

    @Resource
    CustomerGroupMapper customerGroupMapper;
    @Resource
    ProjCustomerMapper customerMapper;
    @Resource
    JdbcTemplate jdbcTemplate;

    public Map getGroupTree() {
        List<CustomerGroup> groupList = customerGroupMapper.selectList(new LambdaQueryWrapper<CustomerGroup>()
                .eq(CustomerGroup::getActive, true)
                .isNotNull(CustomerGroup::getParentId)
        );

        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("customergroupid");
        treeNodeConfig.setParentIdKey("parentId");
        treeNodeConfig.setWeightKey("customergroupid");
        treeNodeConfig.setNameKey("customergroupfullname");
        treeNodeConfig.setDeep(10);

        List<Tree<String>> treeList = TreeUtil.build(groupList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getCustomergroupid());
                    tree.setName(treeNode.getCustomergroupfullname());
                    tree.setParentId(treeNode.getParentId());
                    tree.setWeight(treeNode.getCustomergroupid());
                });


        List<CustomerGroup> pendingGroupList = customerGroupMapper.selectList(new LambdaQueryWrapper<CustomerGroup>()
                .eq(CustomerGroup::getActive, true)
                .isNull(CustomerGroup::getParentId)
        );

        return new HashMap() {
            {
                put("group", treeList);
                put("pendingGroup", pendingGroupList);

            }
        };

    }

    public List<Tree<String>> getAllGroupTree() {
        List<CustomerGroup> groupList = customerGroupMapper.selectList(new LambdaQueryWrapper<CustomerGroup>()
                .eq(CustomerGroup::getActive, true)
                .isNotNull(CustomerGroup::getParentId)
        );

        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("customergroupid");
        treeNodeConfig.setParentIdKey("parentId");
        treeNodeConfig.setWeightKey("customergroupid");
        treeNodeConfig.setNameKey("customergroupfullname");
        treeNodeConfig.setDeep(10);

        List<Tree<String>> treeList = TreeUtil.build(groupList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getCustomergroupid());
                    tree.setName(treeNode.getCustomergroupfullname());
                    tree.setParentId(treeNode.getParentId());
                    tree.setWeight(treeNode.getCustomergroupid());
                });


        return treeList;

    }


    public List<Tree<String>> getTopTwoGroupTree() {
        // 429502380176834625	一级（集团）公司
        // 429502380176834633	二级公司
        // 429502380176834641	三级公司/项目公司
        List<CustomerGroup> groupList = customerGroupMapper.selectList(new LambdaQueryWrapper<CustomerGroup>()
                .eq(CustomerGroup::getActive, true)
                .isNotNull(CustomerGroup::getParentId)
                .in(CustomerGroup::getLevelId, "429502380176834625,429502380176834633".split(","))
        );

        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("customergroupid");
        treeNodeConfig.setParentIdKey("parentId");
        treeNodeConfig.setWeightKey("customergroupid");
        treeNodeConfig.setNameKey("customergroupfullname");
        treeNodeConfig.setDeep(10);

        List<Tree<String>> treeList = TreeUtil.build(groupList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getCustomergroupid());
                    tree.setName(treeNode.getCustomergroupfullname());
                    tree.setParentId(treeNode.getParentId());
                    tree.setWeight(treeNode.getCustomergroupid());
                });

        return treeList;

    }

    public List<CustomerGroup> getGroup(JSONObject node) {
        // 429502380176834625	一级（集团）公司
        // 429502380176834633	二级公司
        // 429502380176834641	三级公司/项目公司
        if (node.getBoolean("root") != null && node.getBoolean("root")) {
            List<CustomerGroup> groupList = customerGroupMapper.selectList(new LambdaQueryWrapper<CustomerGroup>()
                    .eq(CustomerGroup::getActive, true)
                    .eq(CustomerGroup::getLevelId, "429502380176834625")
            );

            return groupList;

        } else {
            List<CustomerGroup> groupList = customerGroupMapper.selectList(new LambdaQueryWrapper<CustomerGroup>()
                    .eq(CustomerGroup::getActive, true)
                    .eq(CustomerGroup::getParentId, node.getString("value"))
            );

            for (CustomerGroup item : groupList) {
                item.setIsLeaf(true);
            }

            return groupList;

        }
    }

    public void saveGroupTree(JSONArray postedData) {
        if (postedData == null) {
            throw new RuntimeException("保存数据为空！");
        }

        this.updateDB(postedData, "0", CustomerGroupConstant.LEVEL_1_ID);

    }


    public CustomerGroup generateOne(String name, String fullName, String groupIdJson) {
        CustomerGroup customerGroup = new CustomerGroup();
        String customerGroupId = IdUtil.getSuid();
        JSONArray groupIdJsonArray = StrUtil.isBlankOrUndefined(groupIdJson) ? new JSONArray() : JSONObject.parseArray(groupIdJson);

        customerGroup.setCustomergroupid(customerGroupId);
        customerGroup.setCustomergroupname(name);
        customerGroup.setCustomergroupfullname(fullName);
        if (groupIdJsonArray.size() == 1) {
            customerGroup.setLevelId(CustomerGroupConstant.LEVEL_2_ID);
        } else {
            customerGroup.setLevelId(CustomerGroupConstant.LEVEL_3_ID);
        }

        if (groupIdJsonArray.size() > 0) {
            customerGroup.setParentId(groupIdJsonArray.get(groupIdJsonArray.size() - 1).toString());
        }

        return customerGroup;
    }


    public void add(CustomerGroup newCustomerGroup, String customerCode) {
        List<CustomerGroup> customerGroupList = customerGroupMapper.selectList(new LambdaQueryWrapper<CustomerGroup>()
                .eq(CustomerGroup::getActive, true)
                .eq(CustomerGroup::getCustomergroupfullname, newCustomerGroup.getCustomergroupfullname()));

        // 新增客户不存在于业主集团，直接添加
        if (customerGroupList.size() == 0) {
            FanUtil.setBaseData(newCustomerGroup);
            newCustomerGroup.setCustomergroupcode(CustomerGroupUtil.getNextCode());
            customerGroupMapper.insert(newCustomerGroup);

            this.updateCustomerGroupId(customerCode, Long.parseLong(newCustomerGroup.getCustomergroupid()));
        }
        // 新增客户存在于业主集团，优先使用新数据，单保留原数据的 customergroupid customergroupcode
        else if (customerGroupList.size() == 1) {
            CustomerGroup oldCustomerGroup = customerGroupList.get(0);
            String customergroupid = oldCustomerGroup.getCustomergroupid();
            String customergroupcode = oldCustomerGroup.getCustomergroupcode();

            BeanUtil.copyProperties(newCustomerGroup, oldCustomerGroup, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            oldCustomerGroup.setCustomergroupid(customergroupid);
            oldCustomerGroup.setCustomergroupcode(customergroupcode);
            oldCustomerGroup.setLastdate(new Date());
            oldCustomerGroup.setLastuid(ContextUtil.getCurrentUserId());

            customerGroupMapper.updateById(oldCustomerGroup);

            this.updateCustomerGroupId(customerCode, Long.parseLong(oldCustomerGroup.getCustomergroupid()));

        } else {
            throw new RuntimeException("[" + newCustomerGroup.getCustomergroupfullname() + "] 在业主集团中存在多条!");
        }


    }

    private void updateCustomerGroupId(String customerCode, long customerGroupId) {
        ProjCustomer customer = customerMapper.selectOne(new LambdaQueryWrapper<ProjCustomer>()
                .eq(ProjCustomer::getActive, true)
                .eq(ProjCustomer::getCustomercode, customerCode));
        customer.setCustomergroupid(customerGroupId);

        customerMapper.updateById(customer);
    }

    private void updateDB(JSONArray jsonArray, String parentId, Long levelId) {
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            CustomerGroup customerGroup = BeanUtil.copyProperties(jsonObject, CustomerGroup.class);
            customerGroup.setParentId(parentId);
            customerGroup.setLevelId(levelId);

            customerGroupMapper.updateById(customerGroup);

            JSONArray children = jsonObject.getJSONArray("children");
            if (children != null) {
                this.updateDB(children, customerGroup.getCustomergroupid(), this.getNextLevelId(levelId));
            }

        }


    }

    // 429502380176834625	一级（集团）公司
    // 429502380176834633	二级公司
    // 429502380176834641	三级公司/项目公司
    private Long getNextLevelId(Long levelId) {
        if (levelId.equals(CustomerGroupConstant.LEVEL_1_ID)) {
            return CustomerGroupConstant.LEVEL_2_ID;
        }

        if (levelId.equals(CustomerGroupConstant.LEVEL_2_ID)) {
            return CustomerGroupConstant.LEVEL_3_ID;
        }

        return CustomerGroupConstant.LEVEL_3_ID;

    }

    public String getGroupIdJson(Long customerGroupId) {

        String sql = "SELECT\n" +
                "    a1.customergroupid id1 ,\n" +
                "    a2.customergroupid id2 ,\n" +
                "    a3.customergroupid id3 ,\n" +
                "    a4.customergroupid id4 ,\n" +
                "    a5.customergroupid id5 \n" +
                "FROM `proj_project_z_customergroup`        AS a1\n" +
                "    LEFT JOIN proj_project_z_customergroup AS a2 ON a1.parent_id = a2.customergroupid\n" +
                "    LEFT JOIN proj_project_z_customergroup AS a3 ON a2.parent_id = a3.customergroupid\n" +
                "    LEFT JOIN proj_project_z_customergroup AS a4 ON a3.parent_id = a4.customergroupid\n" +
                "    LEFT JOIN proj_project_z_customergroup AS a5 ON a4.parent_id = a5.customergroupid\n" +
                "\n" +
                "WHERE\n" +
                "    a1.customergroupid = {}";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(StrUtil.format(sql, customerGroupId));


        ArrayList keyList = new ArrayList<String>() {
            {
                add("id1");
                add("id2");
                add("id3");
                add("id4");
                add("id5");
            }
        };

        ArrayList<String> idList = new ArrayList<>();
        for (int i = keyList.size() - 1; i > -1; i--) {
            String id = FanUtil.toStringIfNullToEmpty(mapList.get(0).get("id" + i));
            if (!StrUtil.isBlankOrUndefined(id)) {
                idList.add(id);
            }
        }

        String jsonString = JSON.toJSONString(idList);

        return jsonString;
    }


}
